/*******************************************************************************
 * Copyright (c) 2014-8-17 @author <a href="mailto:iffiff1@hotmail.com">Tyler Chen</a>.
 * All rights reserved.
 *
 * Contributors:
 *     <a href="mailto:iffiff1@hotmail.com">Tyler Chen</a> - initial API and implementation
 ******************************************************************************/
package com.foreveross.project.projectonline.config;

import java.util.Map.Entry;

import org.iff.infra.util.FCS;
import org.iff.infra.util.Logger;

import com.foreveross.project.projectonline.jfinal.plugin.FreeMarkerExt;
import com.foreveross.project.projectonline.model.TpMgtUser;
import com.foreveross.project.projectonline.util.SpringContextHelper;
import com.foreveross.project.projectonline.web.controller.LoginController;
import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;

import freemarker.ext.beans.BeansWrapper;
import freemarker.template.TemplateModel;

/**
 * @author <a href="mailto:iffiff1@hotmail.com">Tyler Chen</a> 
 * @since 2014-8-17
 */
public class CommonInterceptor implements Interceptor {

	private static TemplateModel springHelper = null;
	private static TemplateModel helper = null;

	public CommonInterceptor() {
		super();
		try {
			springHelper = BeansWrapper.getDefaultInstance().getStaticModels().get(SpringContextHelper.class.getName());
		} catch (Exception e) {
		}
		try {
			helper = BeansWrapper.getDefaultInstance().getStaticModels();
		} catch (Exception e) {
		}
	}

	public void intercept(ActionInvocation ai) {
		Controller controller = ai.getController();
		TpMgtUser user = null;
		{// login test
			if (controller.getClass().isAnnotationPresent(NeedLogin.class)) {//validate login
				Logger.debug("[NeedLogin]");
				Object object = controller.getRequest().getSession().getAttribute(Constants.SESSION_USER_KEY);
				if (object == null || !(object instanceof TpMgtUser)) {
					Logger.debug(FCS.get("[NeedLogin][NoLogin][{0}]", ai.getActionKey()));
					if (!(controller instanceof LoginController || "POST".equalsIgnoreCase(controller.getRequest()
							.getMethod()))) {
						controller.getRequest().getSession().setAttribute(Constants.SESSION_LOGIN_BEFORE_URL,
								ai.getActionKey());
					}
					controller.redirect("/login");
					return;
				} else {
					user = (TpMgtUser) object;
					controller.setAttr("LOGIN_USER", object);
				}
			} else {//no need login
				Logger.debug("[NoNeedLogin]");
			}
		}
		try {
			ai.invoke();
		} finally {
			AfterAIThreadLocal.me().doCounter();
		}
		{// setting common attribute 
			/**
			 * you can use this on ftl like this: ${Spring.getBean('beanName')}
			 */
			controller.setAttr("Spring", springHelper);
			/**
			 * you can use this on ftl like this:${Helper["java.lang.System"].currentTimeMillis()}
			 */
			controller.setAttr("Helper", helper);
			controller.setAttr("request", ai.getController().getRequest());
			controller.setAttr("session", ai.getController().getRequest().getSession());
			{
				for (Entry<String, Object> entry : FreeMarkerExt.getExtMap().entrySet()) {
					controller.setAttr(entry.getKey(), entry.getValue());

				}
			}
		}
	}

}
